package com.tusuo.stds.ui.question;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.tusuo.stds.Constants;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.LevelRecordDetail;
import com.tusuo.stds.rest.LevelRecordList;
import com.tusuo.stds.rest.Question;
import com.tusuo.stds.util.DESedeUtil;
import com.tusuo.stds.util.Utils;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import rx.Subscriber;
import timber.log.Timber;

/**
 * Created by developer on 17-6-14.
 */

@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(LevelRecordDetailPresenter.class)
public class LevelRecordDetailPresenter extends MvpBasePresenter<LevelRecordDetailView> {


    @Inject
    ApiHelper mApiHelper;
    @Inject
    SharedPreferences mSharedPref;

    private Context mContext;
    private String mErrMsgServer;

    private Subscriber<LevelRecordDetail> mGetLevelRecordDetailSubscriber = null;

    private String mSecretKey;

    LevelRecordDetailPresenter(Context context, LevelRecordList.LevelRecord levelRecord, boolean isLevel) {
        mContext = context;
        mErrMsgServer = mContext.getResources().getString(R.string.err_msg_server);

        Injector.initLevelRecordDetailPresenterComponent().inject(this);

        if (isLevel) {
            mGetLevelRecordDetailSubscriber = new GetLevelRecordDetailSubscriber();
            mApiHelper.getLevelRecordDetail(mGetLevelRecordDetailSubscriber, levelRecord.Id);
        }
    }

    @Override
    public void attachView(LevelRecordDetailView view) {
        super.attachView(view);

        if (getView() != null) {
            getView().initFirst();
            if (mSharedPref == null) {
                mSharedPref = PreferenceManager.getDefaultSharedPreferences(mContext);
            }
            mSecretKey = DESedeUtil.getSecretKey(mSharedPref.getString(Constants.KEY_COOKIE, ""));
            getView().setSecretKey(mSecretKey);
        }
    }

    private class GetLevelRecordDetailSubscriber extends Subscriber<LevelRecordDetail> {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            Timber.d(e.toString());
            Utils.UI.showToastShort(mErrMsgServer);
        }

        @Override
        public void onNext(final LevelRecordDetail levelRecordDetail) {
            if (levelRecordDetail.checkState(mContext) && getView() != null) {
                getView().initAdapter(levelRecordDetail);
            }
        }
    }
}
